package cn.galudisu.reactivemanifesto

import akka.actor.ActorRef
import akka.http.scaladsl.model.Uri
import akka.pattern.ask
import akka.util.Timeout
import cn.galudisu.reactivemanifesto.interceptor.InterceptorMagnet._

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
import scala.util.{Failure, Success, Try}

case class Switchgear(mark: Booklet)(implicit ref:ActorRef) {

  import GospelConfig._
  /** 这里不会出现超时的情况，todo 改用promise的实现方式 */
  implicit val timeout: Timeout = Timeout(1.seconds)
  /**
    * 询问该接口是否可用
    */
  def emit(uri: Uri): Either[Zeroline, AC] = {

    val fut: Future[Circuity] = (ref ? mark).mapTo[Circuity]

    val result: Try[Circuity] = Await.ready(fut, Duration.Inf).value.get

    result match {
      case Success(a: AC) => Right(a)
      case Success(z: Zeroline) => Left(z)
      case Failure(_) => Left(Zeroline(name = "ask time out", timeout = call_timeout.seconds))
    }
  }
}
